package com.test.io.basic;

import java.io.*;

/**
 * @author rgsmaster
 * @date 2024/7/23 10:09
 * @description
 */
public class Base {

    public static void main(String[] args) {
        String path = "D:/test.txt";
//        readFile(path);
//        writeFile(path,"追加的内容");
//        readFile(path);
        readFileByFileReader(path);
    }

    //输入流读取文件（我每次读取10个字节），但是一个汉字是有utf8占用3字节，因此会导致乱码
    public static void readFile(String path) {
        FileInputStream fileInputStream = null;
        try {
            //创建一个输入流
            fileInputStream = new FileInputStream(new File(path));
            byte[] readData = new byte[10];
            int bufferSize = 0;
            //如果读取正常，会返回实际读取的字节数
            //fileInputStream.read(readData) 从输入流中读取数据到readData中
            while ((bufferSize = fileInputStream.read(readData)) != -1) {
                System.out.print(new String(readData, 0, bufferSize));
            }

            System.out.println();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//关闭文件流，释放资源
            try {
                //这个异常只要保证的确执行了close操作即可
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //输出流写入文件
    public static void writeFile(String path, String content) {

        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(path, true);
            fileOutputStream.write(content.getBytes());

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    //因为写的是字节，但是我们汉字字节很麻烦，因此考虑是有字符流

    public static void readFileByFileReader(String path) {
        FileReader fileReader = null;
        try {
             fileReader = new FileReader(path);
            char[] chars = new char[3];
            int readLen = 0;

            while ((readLen = fileReader.read(chars)) != -1) {
                System.out.print(new String(chars, 0, readLen));
            }
        } catch (Exception e) {

        } finally {
            try{
                fileReader.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}
